import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
"""pil错误：主要是版本太新了，有些东西已经删了，换个低版本即可，参考https://blog.csdn.net/weixin_45021364/article/details/104600802"""


def data_get001(dir:str):
    #  图像预处理方式  https://blog.csdn.net/weixin_43135178/article/details/115133115
    transform = transforms.Compose(
        [transforms.ToTensor(),
         transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

    trainset = torchvision.datasets.CIFAR10(root='F:/pycharm_test/train_dataset', train=True, download=False,
                                            transform=transform)  # 下载并导入数据训练集
    trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2)  # 加载数据，并分批

    testset = torchvision.datasets.CIFAR10(root='F:/pycharm_test/train_dataset', train=False,
                                           download=False, transform=transform)  # 下载并导入数据测试集
    testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2)  # 加载数据，并分批

    return trainset, trainloader, testset, testloader


# 构建展示图片的函数
def imshow(img):
    img = img / 2 + 0.5
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
    plt.show()

"""         3. 定义神经网络           """
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * 5 * 5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

def train_model_001(net, trainloader, optimizer, criterion, device):
    for epoch in range(2):  # loop over the dataset multiple times

        running_loss = 0.0
        for i, data in enumerate(trainloader, 0):
            # data中包含输入图像张量inputs, 标签张量labels
            # inputs, labels = data
            inputs, labels = data[0].to(device), data[1].to(device)

            # 首先将优化器梯度归零
            optimizer.zero_grad()

            # 输入图像张量进网络, 得到输出张量outputs
            outputs = net(inputs)

            # 利用网络的输出outputs和标签labels计算损失值
            loss = criterion(outputs, labels)

            # 反向传播+参数更新, 是标准代码的标准流程
            loss.backward()
            optimizer.step()

            # 打印轮次和损失值
            running_loss += loss.item()
            if (i + 1) % 2000 == 0:
                print('[%d, %5d] loss: %.3f' %
                      (epoch + 1, i + 1, running_loss / 2000))
                running_loss = 0.0

    print('Finished Training')
    return net

def test_demo(testloader, classes, net, PATH):
    """打印几张图片看看"""
    dataiter = iter(testloader)
    images, labels = dataiter.next()

    # 打印原始图片
    imshow(torchvision.utils.make_grid(images))
    # 打印真实的标签
    print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))

    """调用训练好的模型进行测试"""
    # 首先实例化模型的类对象
    net = Net()
    # 加载训练阶段保存好的模型的状态字典
    net.load_state_dict(torch.load(PATH))

    # 利用模型对图片进行预测
    outputs = net(images)

    # 共有10个类别, 采用模型计算出的概率最大的作为预测的类别
    _, predicted = torch.max(outputs, 1)

    # 打印预测标签的结果
    print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(4)))

def test_accurate001(testloader, net, classes, device):
    class_correct = list(0. for i in range(10))
    class_total = list(0. for i in range(10))
    with torch.no_grad():
        for data in testloader:
            # images, labels = data
            images, labels = data[0].to(device), data[1].to(device)
            outputs = net(images)
            _, predicted = torch.max(outputs, 1)
            c = (predicted == labels).squeeze()
            for i in range(4):
                label = labels[i]
                class_correct[label] += c[i].item()
                class_total[label] += 1

    for i in range(10):
        print('Accuracy of %5s : %2d %%' % (
            classes[i], 100 * class_correct[i] / class_total[i]))


if __name__ == '__main__':
    print('torch.cuda.is_available(): ', torch.cuda.is_available())
    """          1. 获取数据集并加载         """
    trainset, trainloader, testset, testloader = data_get001('F:/pycharm_test/train_dataset')
    classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')

    """         2. 把下载的数据集的图片打开看看           """
    # 从数据迭代器中读取一张图片
    # dataiter = iter(trainloader)
    # images, labels = dataiter.next()
    # # 展示图片
    # imshow(torchvision.utils.make_grid(images))
    # # 打印标签label
    # print(' '.join('%5s' % classes[labels[j]] for j in range(4)))

    """         3. 定义神经网络           """
    net = Net()

    """         4. 定义损失函数           """
    # 采用交叉熵损失函数和随机梯度下降优化器
    criterion = nn.CrossEntropyLoss()
    optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

    """         5. 启用GPU           """
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    net.to(device)

    """         6. 训练模型           """
    # net = train_model_001(net, trainloader, optimizer, criterion, device)

    """         7. 保存模型           """
    # 首先设定模型的保存路径
    PATH = 'F:/pycharm_test/train_dataset/cifar_net.pth'
    # 保存模型的状态字典
    # torch.save(net.state_dict(), PATH)

    """         8. 测试运行           """
    # test_demo(testloader, classes, net, PATH)

    """         9. 测试测试集中的准确率           """
    test_accurate001(testloader, net, classes, device)








